package cn.xwt.weidisk.controller;

import cn.xwt.weidisk.pojo.dao.RecycleDo;
import cn.xwt.weidisk.pojo.dao.UserDo;
import cn.xwt.weidisk.pojo.dto.Resp;
import cn.xwt.weidisk.pojo.dto.SendData;
import cn.xwt.weidisk.pojo.dto.UserData;
import cn.xwt.weidisk.service.CommonService;
import cn.xwt.weidisk.service.FileService;
import cn.xwt.weidisk.service.RecycleService;
import cn.xwt.weidisk.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;

/**
 * @author 薛慰涛
 * 管理员操作
 */
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Resource
    UserService userService;

    @Resource
    CommonService commonService;

    @Resource
    FileService fileService;

    @Resource
    RecycleService recycleService;

    Logger log = LoggerFactory.getLogger(getClass());

    /**
     * 获取用户列表
     * @return List<UserDo>
     */
    @GetMapping("/user-list")
    public List<UserDo> getUserList() {
        return userService.getUserList();
    }

    /**
     * 修改capacity
     * @param user 用户信息
     * @return resp
     */
    @PutMapping("/update-capacity")
    public Resp updateCapacity(@RequestBody UserData user) {
        userService.updateCapacity(user.getId(), user.getCapacity());
        return Resp.success();
    }

    /**
     * 修改locked
     * @param user 用户信息
     * @return resp
     */
    @PutMapping("/update-locked")
    public Resp updateLocked(@RequestBody UserData user) {
        userService.updateLocked(user.getId(), user.getLocked());
        return Resp.success();
    }

    /**
     * 发送邮件信息
     * @param sendData 邮件信息
     * @return resp
     */
    @PostMapping("/send-email")
    public Resp sendEmail(@RequestBody SendData sendData) {
        if (commonService.sendEmail(sendData.getEmail(), sendData.getMsg())) {
            return Resp.success();
        } else {
            return Resp.serverError();
        }
    }

    /**
     * 删除过期文件
     */
    @Scheduled(cron = "0 0 3 * * ?")
    public void deleteExpire() {
        List<RecycleDo> recycleList = recycleService.selectExpireList();
        List<Long> deleteRidList = new LinkedList<>();
        for (RecycleDo recycle : recycleList) {
            deleteRidList.add(recycle.getId());
            recycleService.deleteRecycle(recycle.getId(), null);
        }
        log.info(deleteRidList.toString());
        fileService.deleteFileListComplete(deleteRidList, null);
    }
}
